import router from './router'
import store from './store'
import { Toast } from 'vant'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login','/updatepwd', '/bootpage',  '/register']

router.beforeEach((to, from, next) => {
  NProgress.start()
  console.log('getToken():',getToken());
  if (getToken()) {
    // to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    /* has token*/
    console.log(123123);
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      // console.log('store.getters.userName:',store.getters.userName);
      if (!store.getters.user) {
        if(to.path == '/userinfo'){ //如果已经跳转到个人信息页
          next();
        }else{
          // 判断当前用户是否已拉取完user_info信息
          store.dispatch('user/getInfo').then((data) => {
            if(!data){//没有个人信息页跳转到完善个人信息页面
              next({path:'/userinfo'})
            }else{
              next();
            }
          }).catch(err => {
            store.dispatch('user/logout').then(() => {
              Toast(err);
              next({ path: '/' })
              NProgress.done()
            })
          })
        }
        
      } else {
        next()
      }
    }
  } else {
    // 没有token
    console.log(2222222222222222);
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
